import { useState, useEffect } from "react";
import { useNavigate, useSearchParams } from "react-router-dom";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { Separator } from "@/components/ui/separator";
import { User, Upload, ArrowLeft, Save, Camera } from "lucide-react";
import { useUser, DEFAULT_AVATARS } from "@/contexts/UserContext";
import { useToast } from "@/hooks/use-toast";

const Profile = () => {
  const [searchParams] = useSearchParams();
  const isFirstTime = searchParams.get("first") === "true";

  const { user, updateProfile } = useUser();
  const { toast } = useToast();
  const navigate = useNavigate();

  const [formData, setFormData] = useState({
    nickname: "",
    avatar: "",
    password: "",
  });
  const [showAvatarPicker, setShowAvatarPicker] = useState(false);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (user) {
      setFormData({
        nickname: user.nickname || "",
        avatar: user.avatar || "",
        password: "",
      });
    }
  }, [user]);

  // 选择默认头像
  const handleAvatarSelect = (avatar: string) => {
    setFormData((prev) => ({ ...prev, avatar }));
    setShowAvatarPicker(false);
  };

  // 上传自定义头像
  const handleAvatarUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        const result = e.target?.result as string;
        setFormData((prev) => ({ ...prev, avatar: result }));
      };
      reader.readAsDataURL(file);
    }
  };

  // 保存个人信息
  const handleSave = async () => {
    if (!formData.nickname.trim()) {
      toast({
        title: "错误",
        description: "请输入昵称",
        variant: "destructive",
      });
      return;
    }

    if (!formData.avatar) {
      toast({
        title: "错误",
        description: "请选择或上传头像",
        variant: "destructive",
      });
      return;
    }

    setLoading(true);
    // 模拟保存过程
    setTimeout(() => {
      setLoading(false);
      updateProfile({
        nickname: formData.nickname.trim(),
        avatar: formData.avatar,
        isProfileComplete: true,
      });

      toast({
        title: "保存成功",
        description: "个人信息已更新",
      });

      if (isFirstTime) {
        navigate("/");
      }
    }, 1000);
  };

  if (!user) {
    navigate("/login");
    return null;
  }

  return (
    <div className="min-h-screen bg-background">
      <div className="container max-w-2xl py-8 space-y-8">
        {/* 头部 */}
        <div className="flex items-center justify-between">
          <div className="flex items-center space-x-4">
            <Button
              variant="ghost"
              size="sm"
              onClick={() => navigate(isFirstTime ? "/" : "/")}
              className="flex items-center gap-2"
            >
              <ArrowLeft className="h-4 w-4" />
              {isFirstTime ? "跳过" : "返回"}
            </Button>
            <div>
              <h1 className="text-2xl font-bold">个人信息</h1>
              <p className="text-muted-foreground">
                {isFirstTime
                  ? "完善您的个人信息，开启智能视频分析之旅"
                  : "管理您的个人资料"}
              </p>
            </div>
          </div>
          {isFirstTime && (
            <Badge variant="secondary" className="bg-warning/10 text-warning">
              首次设置
            </Badge>
          )}
        </div>

        <Card className="shadow-[var(--shadow-card)] border-0">
          <CardHeader className="bg-[var(--gradient-secondary)] rounded-t-lg">
            <CardTitle className="flex items-center gap-2">
              <User className="h-5 w-5 text-primary" />
              基本信息
            </CardTitle>
            <CardDescription>设置您的头像、昵称等基本信息</CardDescription>
          </CardHeader>

          <CardContent className="p-6 space-y-6">
            {/* 头像设置 */}
            <div className="space-y-4">
              <Label className="text-base font-medium">头像 *</Label>
              <div className="flex items-start space-x-4">
                <div className="relative">
                  <Avatar className="h-20 w-20 ring-4 ring-primary/20 hover:ring-primary/40 transition-[var(--transition-smooth)]">
                    <AvatarImage src={formData.avatar} alt="用户头像" />
                    <AvatarFallback className="bg-[var(--gradient-primary)] text-primary-foreground">
                      <User className="h-8 w-8" />
                    </AvatarFallback>
                  </Avatar>
                  <Button
                    size="sm"
                    variant="outline"
                    className="absolute -bottom-2 -right-2 h-8 w-8 rounded-full p-0 shadow-[var(--shadow-button)]"
                    onClick={() => setShowAvatarPicker(!showAvatarPicker)}
                  >
                    <Camera className="h-3 w-3" />
                  </Button>
                </div>
                <div className="space-y-2">
                  <Button
                    variant="outline"
                    onClick={() => setShowAvatarPicker(!showAvatarPicker)}
                    className="w-full"
                  >
                    选择默认头像
                  </Button>
                  <div className="relative">
                    <input
                      id="avatar-upload"
                      type="file"
                      accept="image/*"
                      onChange={handleAvatarUpload}
                      className="hidden"
                    />
                    <Button
                      variant="outline"
                      onClick={() =>
                        document.getElementById("avatar-upload")?.click()
                      }
                      className="w-full"
                    >
                      <Upload className="h-4 w-4 mr-2" />
                      上传头像
                    </Button>
                  </div>
                </div>
              </div>

              {/* 头像选择器 */}
              {showAvatarPicker && (
                <Card className="p-4 bg-accent/50">
                  <div className="grid grid-cols-5 gap-3">
                    {DEFAULT_AVATARS.map((avatar, index) => (
                      <Button
                        key={index}
                        variant="ghost"
                        className="h-16 w-16 p-0 rounded-full hover:scale-110 transition-[var(--transition-smooth)]"
                        onClick={() => handleAvatarSelect(avatar)}
                      >
                        <Avatar className="h-14 w-14">
                          <AvatarImage
                            src={avatar}
                            alt={`默认头像 ${index + 1}`}
                          />
                          <AvatarFallback>
                            <User className="h-6 w-6" />
                          </AvatarFallback>
                        </Avatar>
                      </Button>
                    ))}
                  </div>
                </Card>
              )}
            </div>

            <Separator />

            {/* 昵称设置 */}
            <div className="space-y-2">
              <Label htmlFor="nickname" className="text-base font-medium">
                昵称 *
              </Label>
              <Input
                id="nickname"
                placeholder="请输入昵称"
                value={formData.nickname}
                onChange={(e) =>
                  setFormData((prev) => ({ ...prev, nickname: e.target.value }))
                }
                className="text-base"
              />
            </div>

            <Separator />

            {/* 密码设置 */}
            <div className="space-y-2">
              <Label htmlFor="password" className="text-base font-medium">
                设置密码
              </Label>
              <Input
                id="password"
                type="password"
                placeholder="可选，设置登录密码"
                value={formData.password}
                onChange={(e) =>
                  setFormData((prev) => ({ ...prev, password: e.target.value }))
                }
                className="text-base"
              />
              <p className="text-sm text-muted-foreground">
                设置密码后，您可以使用手机号+密码或验证码登录
              </p>
            </div>

            <Separator />

            {/* 账户信息 */}
            <div className="bg-muted/50 p-4 rounded-lg space-y-2">
              <h4 className="font-medium">账户信息</h4>
              <div className="grid grid-cols-2 gap-4 text-sm">
                <div>
                  <span className="text-muted-foreground">手机号：</span>
                  <span className="font-mono">{user.phone}</span>
                </div>
                <div>
                  <span className="text-muted-foreground">当前积分：</span>
                  <span className="font-bold text-primary">{user.credits}</span>
                </div>
              </div>
            </div>

            {/* 保存按钮 */}
            <div className="flex gap-3">
              <Button
                onClick={handleSave}
                disabled={
                  loading || !formData.nickname.trim() || !formData.avatar
                }
                className="flex-1 bg-[var(--gradient-primary)] hover:shadow-[var(--shadow-button)] transition-[var(--transition-smooth)]"
                size="lg"
              >
                {loading ? (
                  "保存中..."
                ) : (
                  <>
                    <Save className="h-4 w-4 mr-2" />
                    保存信息
                  </>
                )}
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
};

export default Profile;
